package com.chat.mapper;

import com.chat.entry.po.UserMessage;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

/**
 * <p>
 * 用户聊天表 Mapper 接口
 * </p>
 *
 * @author author
 * @since 2025-08-21
 */
public interface UserMessageMapper extends BaseMapper<UserMessage> {

    @Update("UPDATE user_message um " +
            "SET um.read_status = 1 " +
            "WHERE um.receiver_id = #{userId} AND um.read_status = 0")
    int updateAllFriendMessages(Integer userId);

    @Select("SELECT um.* " +
            "FROM user_message um " +
            "JOIN ( " +
            "    SELECT CASE WHEN sender_id = #{userId} THEN receiver_id ELSE sender_id END AS contact_id, " +
            "           MAX(send_time) AS last_time " +
            "    FROM user_message " +
            "    WHERE sender_id = #{userId} OR receiver_id = #{userId} " +
            "    GROUP BY contact_id " +
            ") t " +
            "ON ( (um.sender_id = #{userId} AND um.receiver_id = t.contact_id) " +
            "  OR (um.receiver_id = #{userId} AND um.sender_id = t.contact_id) ) " +
            "AND um.send_time = t.last_time " +
            "ORDER BY um.send_time DESC")
    List<UserMessage> selectLastMessages(@Param("userId") Integer userId);

}
